import ctypes
import subprocess
import json

import numpy as np
from PyQt6.QtCore import QObject, pyqtSignal
from PyQt6.QtWidgets import QMessageBox


class Probe(QObject):
    # 定义信号
    probe_signal = pyqtSignal(int)
    received_data = []
    def __init__(self):
        super().__init__()

    def run_32bit_python(self, param1, param2, param3, param4):
        """
        调用32位子程序，传递参数并捕获输出。
        """
        try:
            result = subprocess.run(
                [r"D:\py312withx86\python.exe", "探头32子程序.py", str(param1), str(param2), str(param3), str(param4)],
                check=True,
                capture_output=True,
                text=True,
                encoding="utf-8"
            )
            # QMessageBox.information(None, "探头测试", f"子程序输出:\n{result.stdout}")
        except subprocess.CalledProcessError as e:
            error_msg = e.stderr or e.stdout or "未知错误"
            QMessageBox.warning(None, "探头测试失败", f"错误:\n{error_msg}\n退出代码: {e.returncode}")

    def run_32bit_python_test(self):
        """
        测试能否连接顺畅，返回True表示连接成功。
        """
        try:
            result = subprocess.run(
                [r"D:\py312withx86\python.exe", "探头测试程序.py"],
                check=True,
                capture_output=True,
                text=True,
                encoding="utf-8",
            )
            QMessageBox.information(None, "探头测试", "探头测试成功！")
            self.probe_signal.emit(1)
            return True
        except subprocess.CalledProcessError as e:
            stdout = e.stdout or "无标准输出"
            stderr = e.stderr or "无错误输出"
            QMessageBox.warning(None, "探头测试", f"子程序出错:\n退出代码: {e.returncode}\n输出: {stdout}\n错误: {stderr}")
            self.probe_signal.emit(0)
            return False

    def set_parameter(self, mainwindow):
        """
        读取MainWindow参数并设置给子程序。
        """
        if not self.run_32bit_python_test():
            return

        zero = ctypes.c_int(0)

        self.run_32bit_python(1016, 0, 1, 0)  # 软件触发模式
        self.run_32bit_python(1002, 0, mainwindow.Sample_rate.currentIndex(), 0)  # 采样率
        self.run_32bit_python(1004, 0, mainwindow.low_filter.value(), 0)  # 低通滤波
        self.run_32bit_python(1005, 0, mainwindow.high_filter.value(), 0)  # 高通滤波
        self.run_32bit_python(1006, 0, mainwindow.Wave_Form.currentIndex(), 0)  # 整流类型
        self.run_32bit_python(1008, 0, mainwindow.Model.currentIndex(), 0)  # 传感器模式
        self.run_32bit_python(1009, 0, mainwindow.buffer_length.value(), 0)  # 缓冲区长度
        self.run_32bit_python(1010, 0, mainwindow.receive_delay.value(), 0)  # 接收延时
        self.run_32bit_python(1011, 0, mainwindow.slider_pluse_v.value(), 0)  # 脉冲电压值
        self.run_32bit_python(1012, 0, mainwindow.slider_pluse_w.value(), 0)  # 脉冲电压宽度
        self.run_32bit_python(1013, 0, mainwindow.slider_DB.value(), 0)  # 增益
        self.run_32bit_python(1014, 0, mainwindow.slider_DC.value(), 0)  # 直流偏置
        self.run_32bit_python(1030, 0, mainwindow.TX_channel.currentIndex(),
                              mainwindow.RX_channel.currentIndex())  # 发送接收通道
        self.run_32bit_python(1047, 0, mainwindow.hardfilter.currentIndex(), 0)  # 硬件滤波
        self.run_32bit_python(1075, 0, 0, mainwindow.Aver.value())  # 平均
        self.run_32bit_python(1001, 0, 0, 0)  # 软件触发脉冲

    def save_data(self,mainwindow):
        """
        保存数据到JSON文件并读取数据。
        """
        try:
            data_file = r"F:\pyQT\机械臂控制\data.json"
            # 清空文件内容
            with open(data_file, "w") as f:
                f.truncate(0)
            subprocess.run(
                [r"D:\py312withx86\python.exe", "探头数据保存.py"],
                check=True,
            )

            with open(data_file, "r") as f:
                self.received_data = json.load(f)
            # for i in range(2000):
            #     self.received_data.append(np.random.uniform(0, 200,1))
            self.probe_signal.emit(2)
        except subprocess.CalledProcessError as e:
            print(f"子程序执行失败: {e}")
        except FileNotFoundError:
            print("数据文件未找到，请检查子程序是否正确运行。")
        except Exception as e:
            print(f"发生未知错误: {e}")
